//
//  HZMUserViewController.m
//  糖糖大魔王
//
//  Created by 韩震明 on 15/10/22.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "HZMUserViewController.h"
#import "HZMSettingVC.h"
#import "HZMProtectCVC.h"

@interface HZMUserViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic, retain) UIScrollView *scrollView;
@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UIButton *leftButton;
@property(nonatomic, retain) UIButton *rightButton;
//@property(nonatomic, retain) UIImageView *photo;
//@property(nonatomic, retain) HZMHomePageTopic *topicModel;
@property(nonatomic, retain) NSMutableArray *topicArr;
@property(nonatomic, retain) HZMOtherView *listModel;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, retain) HZMPics *picsModeld;

@property(nonatomic, retain)UMSocialSnsPlatform *snsPlatform;

@property(nonatomic, retain) UIImageView *img;
@property(nonatomic, retain) NSData *fileData;

@end

@implementation HZMUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self navigationSet];
    
    [self createView];
    
    [self setButton];
    
    [self createScrollView];
    
    [self createCollectionView];
    
    [self createTableView];
    
//    [self createData];
    
}



#pragma mark - Navigation Setting
#pragma mark Navigation Setting
- (void)navigationSet
{
//    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    leftButton.frame = CGRectMake(0, 0, 40, 40);
//    [leftButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
//    [self.view addSubview:leftButton];
//    [leftButton addTarget:self action:@selector(leftButton:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:leftButton] autorelease];
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 40, 40);
    [rightButton setImage:[UIImage imageNamed:@"Card"] forState:UIControlStateNormal];
    [self.view addSubview:rightButton];
    [rightButton addTarget:self action:@selector(rightButtonClikl:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease];
    
    self.navigationController.navigationBar.translucent = NO;
}

#pragma mark Navigationbar ButtonAction
- (void)rightButtonClikl:(UIButton *)rightButton
{
    HZMSettingVC *setVC = [[HZMSettingVC alloc] init];
    [self.navigationController pushViewController:setVC animated:YES];
}

//- (void)leftButton:(UIButton *)leftButton
//{
//    //        当用户使用第三方账号（如新浪微博）登录时，可以这样统计：
//    
//    [MobClick profileSignInWithPUID:@"playerID" provider:@""];
//    
//    //     在新浪微博登录按钮中实现下面的方法
//    self.snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
//    
//    self.snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//        
//        //          获取微博用户名、uid、token等
//        
//        if (response.responseCode == UMSResponseCodeSuccess) {
//            
//            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
//            
//            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
//            
//            [self.img sd_setImageWithURL:[NSURL URLWithString:snsAccount.iconURL]];
//            
//        }});
//    
//    //        在授权完成后调用获取用户信息的方法
//    
//    //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
//    [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
//        NSLog(@"SnsInformation is %@",response.data);
//        
//        
//        
//    }];
//}



- (void)createView
{
    UIImageView *headView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    headView.image = [UIImage imageNamed:@"backOfUser"];
    [self.view addSubview:headView];
    [headView release];
    headView.userInteractionEnabled = YES;
    
//    self.img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50 * WIDTH / 414, 50 * HEIGHT / 736)];
//    [headView addSubview:self.img];
//    [self.img release];
//    self.img.center = headView.center;
////    self.img.image = [UIImage imageNamed:@"Pay_Attention"];
//    [self judgeImg];
//    self.img.layer.cornerRadius = 25;
//    self.img.userInteractionEnabled = YES;
//    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userPhotoChange:)];
//    [self.img addGestureRecognizer:tap];
//    [tap release];
}

//- (void)judgeImg
//{
//    NSFileManager *manager = [NSFileManager defaultManager];
//    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *selfPhotoPath = [sandBoxPath stringByAppendingPathComponent:@"selfPhoto.jpg"];
//    
//    
//    if (![manager fileExistsAtPath:selfPhotoPath]) {
//        self.img.image = [UIImage imageNamed:@"Pay_Attention"];
//    } else {
//        
//        self.img.image = [UIImage imageWithContentsOfFile:selfPhotoPath];
//    }
//    NSLog(@"%@", selfPhotoPath);
//}

//#pragma mark Photo Click Method
//- (void)userPhotoChange:(UIButton *)userPhoto
//{
////    保存图片方法
////    UIImageWriteToSavedPhotosAlbum(self.photo.image, self, @selector(imageToPhotosAlbum:Error:contextinfo:), nil);
//    
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    
//    UIAlertAction *head = [UIAlertAction actionWithTitle:@"修改头像" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
////        UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
////        //设置图片源(相簿)
////        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
////        //设置代理
////        picker.delegate = self;
////        //设置可以编辑
////        picker.allowsEditing = YES;
////        //打开拾取器界面
////        [self presentViewController:picker animated:YES completion:nil];
//        
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            imagePicker.delegate = self;
//            imagePicker.allowsEditing = YES;
//            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//            //            [self presentModalViewController:imagePicker animated:YES];
//            [self presentViewController:imagePicker animated:YES completion:nil];
//            
//        }];
//        
//        UIAlertAction *video = [UIAlertAction actionWithTitle:@"摄像机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            imagePicker.delegate = self;
//            imagePicker.allowsEditing = YES;
//            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//            imagePicker.videoQuality = UIImagePickerControllerQualityTypeLow;
//            //            [self presentModalViewController:imagePicker animated:YES];
//            [self presentViewController:imagePicker animated:YES completion:nil];
//            
//        }];
//        
//        UIAlertAction *earthPhoto = [UIAlertAction actionWithTitle:@"本体相簿" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            imagePicker.delegate = self;
//            imagePicker.allowsEditing = YES;
//            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            //            [self presentModalViewController:imagePicker animated:YES];
//            [self presentViewController:imagePicker animated:YES completion:nil];
//            
//        }];
//        
//        UIAlertAction *earthVideo = [UIAlertAction actionWithTitle:@"本地视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//            imagePicker.delegate = self;
//            imagePicker.allowsEditing = YES;
//            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            //            [self presentModalViewController:imagePicker animated:YES];
//            [self presentViewController:imagePicker animated:YES completion:nil];
//            
//        }];
//        
//        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//            
//        }];
//        
//        [alert addAction:camera];
//        [alert addAction:video];
//        [alert addAction:earthPhoto];
//        [alert addAction:earthVideo];
//        [alert addAction:cancel];
//        [self presentViewController:alert animated:YES completion:nil];
//        
//    }];
//    
//    UIAlertAction *userName = [UIAlertAction actionWithTitle:@"修改昵称" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        // self.laber.text = ...;
//        NSLog(@"changeNameSuccess");
//    }];
//    
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    
//    [alert addAction:head];
//    [alert addAction:userName];
//    [alert addAction:cancel];
//    [self presentViewController:alert animated:YES completion:nil];
//}
//
//#pragma mark info
//- (void)imageToPhotosAlbum:(UIImage *)image Error:(NSError *)error contextinfo:(NSString *)info
//{
//    if (!error) {
//        NSLog(@"保存成功");
//    }
//}
//
//#pragma mark -
//#pragma UIImagePickerController Delegate
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
//        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
//        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
//    }
//    else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeMovie]) {
//        NSString *videoPath = (NSString *)[[info objectForKey:UIImagePickerControllerMediaURL] path];
//        self.fileData = [NSData dataWithContentsOfFile:videoPath];
//    }
//    //    [picker dismissModalViewControllerAnimated:YES];
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}
//
//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
//{
//    //    [picker dismissModalViewControllerAnimated:YES];
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}
//
//- (void)saveImage:(UIImage *)image {
//    //    NSLog(@"保存头像！");
//    //    [userPhotoButton setImage:image forState:UIControlStateNormal];
//    BOOL success;
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSError *error;
//    
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
//    NSLog(@"imageFile->>%@",imageFilePath);
//    success = [fileManager fileExistsAtPath:imageFilePath];
//    if(success) {
//        success = [fileManager removeItemAtPath:imageFilePath error:&error];
//    }
//    //    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
//    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
//    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
//    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
//    //    [userPhotoButton setImage:selfPhoto forState:UIControlStateNormal];
//    self.img.image = selfPhoto;
//}
//
//// 改变图像的尺寸，方便上传服务器
//- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
//{
//    UIGraphicsBeginImageContext(size);
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return newImage;
//}
//
//2.保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}




#pragma mark -
#pragma Top Button
- (void)setButton
{
    UIImage *leftImage = [self thumbnailWithImageWithoutScale:[UIImage imageNamed:@"4"] size:CGSizeMake(50, 50)];
    UIImage *rightImage = [self thumbnailWithImageWithoutScale:[UIImage imageNamed:@"7"] size:CGSizeMake(50, 50)];
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftButton.frame = CGRectMake(0, HEIGHT / 3, WIDTH / 2, 44 * HEIGHT / 736);
    [_leftButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_leftButton setImage:leftImage forState:UIControlStateNormal];
    [_leftButton setTitle:@"单品" forState:UIControlStateNormal];
    [self.leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_leftButton];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.frame = CGRectMake(WIDTH / 2, HEIGHT / 3, WIDTH /2, 44 * HEIGHT / 736);
    [_rightButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setImage:rightImage forState:UIControlStateNormal];
    [_rightButton setTitle:@"专题" forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_rightButton];
}

#pragma mark Button Click Method
- (void)Button:(UIButton *)sender
{
    if (sender == self.leftButton) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}



#pragma mark -
#pragma mark Create ScrollView
- (void)createScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, HEIGHT / 3 + 44 * HEIGHT / 736, WIDTH, (736 - 265 - 44 - 44) * HEIGHT / 736)];
    [self.view addSubview:self.scrollView];
    [_scrollView release];
    self.scrollView.contentSize = CGSizeMake(2 * WIDTH, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
}

#pragma mark ScrollView Delegate Method
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == 0) {
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}



#pragma mark -
#pragma mark CreateCollectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(200 * WIDTH / 414, 200 * HEIGHT / 736);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, self.scrollView.frame.size.height - 44) collectionViewLayout:flowLayout];
    [self.scrollView addSubview:self.collectionView];
    [_collectionView release];
    
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.contentInset = UIEdgeInsetsMake(5, 5, 0, 0);
    
    [self.collectionView registerClass:[HZMProtectCVC class] forCellWithReuseIdentifier:@"product"];
    
}

#pragma mark CollectionView Delegate Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.productArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZMProtectCVC *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"product" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor yellowColor];
    self.picsModeld = [[HZMPics alloc] init];
    self.picsModeld = [self.productArr[indexPath.row] pics][0];
    self.listModel = [[HZMOtherView alloc] init];
    self.listModel = self.productArr[indexPath.row];
    NSDictionary *dic = (NSDictionary *)self.picsModeld;

    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"url"]]];
    cell.desc.text = self.listModel.content;
    NSLog(@"%@", cell.desc.text);
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"success");
}



#pragma mark -
#pragma mark Create TableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, self.scrollView.frame.size.height) style:UITableViewStylePlain];
    [self.scrollView addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setEditing:NO animated:YES];
//    self.tableView.bounces = NO;
    self.tableView.userInteractionEnabled = YES;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"topic"];
}

#pragma mark TableView Delegate Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"topic"];
    HZMHomePageTopic *topic = [[HZMHomePageTopic alloc] init];
    topic = self.topicArr[indexPath.row];
    cell.textLabel.text = topic.title;
    
    return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // 这个方法默认就是所有行都可以进行编辑
    return YES;
}

// 实现删除功能
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除 一定要删除对应数据源的数据
        [[DataBaseHandle sharDataVaseHandle] deleteStu:self.topicArr[indexPath.row]];
        [self.topicArr removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}




- (void)createData
{
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[DataBaseHandle sharDataVaseHandle] openDb];
    [[DataBaseHandle sharDataVaseHandle] createTable];
    self.topicArr = [NSMutableArray array];
    self.topicArr = [[DataBaseHandle sharDataVaseHandle] selectTopic];
    
    if ([SaveTool reload] != nil) {
        self.productArr = [NSMutableArray array];
        self.productArr = [SaveTool reload];
    }
    [self.tableView reloadData];
    [self.collectionView reloadData];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
